package cn.itcast.gateway;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

//配置全局过滤器
@Component
//设置优先级，数字越小，级别越高
@Order(-1)
public class AuthorizeFilter implements GlobalFilter {
    /**
     *
     * @param exchange  上下文对象
     * @param chain  过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> params = request.getQueryParams();
        String username = params.getFirst("authorization");
        //校验
        if ("admin".equals(username)) {
            //放行
            return chain.filter(exchange);
        }
        //拦截，设置状态码
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);

        //结束处理
        return exchange.getResponse().setComplete();
    }
}